import { setCredentialFeature } from "@aws-sdk/core/client";
import { AttributedAwsCredentialIdentity, CredentialProviderOptions } from "@aws-sdk/types";
import { CredentialsProviderError } from "@smithy/property-provider";
import type { AwsCredentialIdentityProvider } from "@smithy/types";
import { fileIo as fs } from '@kit.CoreFileKit';

import { fromWebToken, FromWebTokenInit } from "./fromWebToken";
import { util } from "@kit.ArkTS";

const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
const ENV_ROLE_ARN = "AWS_ROLE_ARN";
const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";

/**
 * @public
 */
export interface FromTokenFileInit
  extends Partial<Omit<FromWebTokenInit, "webIdentityToken">>,
    CredentialProviderOptions {
  /**
   * File location of where the `OIDC` token is stored.
   */
  webIdentityTokenFile?: string;
}

/**
 * @internal
 *
 * Represents OIDC credentials from a file on disk.
 */
export const fromTokenFile =
  (init: FromTokenFileInit = {}): AwsCredentialIdentityProvider =>
  async () => {
    init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
    const webIdentityTokenFile = init?.webIdentityTokenFile ;
    const roleArn = init?.roleArn ;
    const roleSessionName = init?.roleSessionName ;

    if (!webIdentityTokenFile || !roleArn) {
      throw new CredentialsProviderError("Web identity configuration not specified", {
        logger: init.logger,
      });
    }

    const credentials: AttributedAwsCredentialIdentity = await fromWebToken({
      ...init,
      webIdentityToken: await readFile(webIdentityTokenFile, "ascii"),
      roleArn,
      roleSessionName,
    })();

    // if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
    //   setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
    // }

    return credentials;
  };
export const readFile= async (filePath:string, encode?:string): Promise<any>=>{
  if (encode && encode.toLowerCase()==='utf8') {
    encode = 'utf-8'
  }
  let isExist = await fs.access(filePath);
  if (!isExist) {
    throw new Error(`File ${filePath} does not exist`);
  }
  const file = await fs.open(filePath, fs.OpenMode.READ_WRITE);
  const fileStat = await fs.stat(filePath);
  const fileSize = fileStat.size;
  let arrayBuffer = new ArrayBuffer(fileSize);
  await fs.read(file.fd, arrayBuffer);
  await fs.close(file.fd);

  const textDecoder = util.TextDecoder.create(encode)
  const result = textDecoder.decodeToString(new Uint8Array(arrayBuffer));
  return JSON.parse(result)
}